import { defineStore } from 'pinia';
import { useWebsocketStore } from '@stores/websocketStore.ts';
import { MessageBean } from '@/beans/message_bean';
import { ref } from 'vue';

export const useLogStore = defineStore('log', () => {
  const messages = ref<MessageBean[]>([]);
  const websocketStore = useWebsocketStore();

  function handleMessageLog(data: string) {
    console.log('logStore 收到消息', data);
    const messageLog = MessageBean.fromJson(JSON.parse(data));
    console.log('logStore 解析消息', messageLog);
    messages.value.unshift(messageLog);
  }

  function unBindWebSocketListener() {
    websocketStore.unsubscribe('message_log', handleMessageLog);
  }

  function setupWebSocketListener() {
    websocketStore.subscribe('message_log', handleMessageLog);
  }

  function clearMessages() {
    messages.value = [];
  }

  async function fetchMessages() {
    try {
      // 这里应该是从后端 API 获取消息的逻辑
      // 暂时使用模拟数据
      const mockMessages: MessageBean[] = [];
      messages.value = mockMessages;
    } catch (error) {
      console.error('Failed to fetch messages:', error);
    }
  }

  return {
    // state
    messages,
    // actions
    handleMessageLog,
    unBindWebSocketListener,
    setupWebSocketListener,
    clearMessages,
    fetchMessages,
  };
});
